package com.bitmap.mysqlite;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class BitmapHelper {

	public static void savebitmap(Context context, String uid, Bitmap bitmap){
		String INSERT_SQL = "INSERT INTO person(photo,uid) values(?,?)";
		MySQLite sqLite = new MySQLite(context, 1);
		SQLiteDatabase db = sqLite.getWritableDatabase();
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, bos);//压缩为PNG格式,100表示跟原图大小一样
			Object[] args = new Object[] {bos.toByteArray(), uid};
			db.execSQL(INSERT_SQL, args);
			Log.e("保存本地图片", uid);
			bos.close();
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Bitmap readbitmap(Context context, String str){
		Bitmap bitmap = null;
		String SELECT_SQL = "SELECT * FROM person where uid="+str;
		MySQLite sqLite = new MySQLite(context, 1);
		SQLiteDatabase db = sqLite.getReadableDatabase();
		Cursor mCursor = db.rawQuery(SELECT_SQL, null);
		byte[] photo = null;
		if(mCursor != null){
			if(mCursor.moveToFirst()){
				photo = mCursor.getBlob(mCursor.getColumnIndex("photo"));//取出图片
			}
		}
		if(mCursor != null){
			mCursor.close();
		}
		db.close();
		ByteArrayInputStream bis = null;
		if(photo != null){
			bis = new ByteArrayInputStream(photo);
			Drawable drawable = Drawable.createFromStream(bis, "photo");
			BitmapDrawable bd = (BitmapDrawable) drawable;
			bitmap = bd.getBitmap();
		}
		Log.e("读取本地数据图片", str);
		return bitmap;
	}
}
